<template>
  <div class="container">
    <div class="header">
      <div class="search-bar">
        <!-- 课程名 -->
        <span class="label">课程名：</span>
        <el-input
          v-model="searchForm.courseName"
          placeholder="请输入课程名"
          class="input"
          clearable
        ></el-input>

        <!-- 课程号 -->
        <span class="label">课程号：</span>
        <el-input
          v-model="searchForm.courseNo"
          placeholder="请输入课程号"
          class="input"
          clearable
        ></el-input>

        <!-- 查询按钮 -->
        <el-button
          type="primary"
          style="margin-right: 20px"
          icon="el-icon-search"
          @click="handleSearch"
        >
          查询
        </el-button>

        <!-- 院系 -->
        <span class="label">院系：</span>
        <el-select
          v-model="searchForm.deptId"
          placeholder="请选择院系"
          class="select"
          @change="selectChange"
          clearable
        >
          <el-option
            v-for="dept in departments"
            :key="dept.id"
            :label="dept.deptName"
            :value="dept.id"
          ></el-option>
        </el-select>

        <!-- 添加按钮 -->
        <el-button
          type="primary"
          icon="el-icon-plus"
          class="add-btn"
          @click="handleAdd"
        >
          添加课程
        </el-button>
      </div>
    </div>
    <div>
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column
          prop="deptName"
          label="开设院系"
          width="150"
          align="center"
        />
        <el-table-column prop="courseName" label="课程名称" align="center" />
        <el-table-column prop="courseNo" label="课程编号" align="center" />
        <el-table-column prop="credit" label="学分" width="80" align="center" />
        <el-table-column prop="hours" label="学时" width="80" align="center" />
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="updateCourse(row)"
              size="mini"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteCourse(row)"
              size="mini"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px; text-align: center">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[2, 5, 8, 10]"
        />
      </div>
    </div>

    <!-- 添加或者修改按钮 -->
    <el-dialog
      :title="form.id ? '编辑课程' : '添加课程'"
      :visible.sync="dialogVisible"
      @close="handleDialogClose"
    >
      <el-form :model="form" label-width="90px" :rules="rules" ref="courseForm">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" />
        </el-form-item>
        <el-form-item label="课程编号" prop="courseNo">
          <el-input v-model="form.courseNo" />
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input-number
            v-model="form.credit"
            :min="1"
            :step="1"
            :precision="0"
            @wheel.native.prevent
          />
        </el-form-item>
        <el-form-item label="学时" prop="hours">
          <el-input-number
            v-model="form.hours"
            :min="1"
            :step="1"
            :precision="0"
            @wheel.native.prevent
          />
        </el-form-item>
        <el-form-item label="开设院系" prop="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择"
            :disabled="form.courseId != null"
          >
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.deptName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="saveCourse">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllDeptCourseDetail } from "@/api/deptcourse";
import { addCourse, deleteCourse, updateCourse } from "@/api/course";
import { mapState } from "vuex";
export default {
  name: "CourseManage",

  computed: {
    ...mapState("dept", ["departments"]),
  },
  data() {
    return {
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 5,
      searchForm: {
        courseName: "",
        courseNo: "",
        deptId: null,
      },

      dialogVisible: false,
      form: {
        courseId: null,
        courseName: "",
        courseNo: "",
        credit: 0,
        hours: 0,
        deptId: null,
      },

      rules: {
        courseName: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
        ],
        courseNo: [
          { required: true, message: "请输入课程编号", trigger: "blur" },
        ],
        credit: [
          {
            required: true,
            type: "number",
            message: "请输入学分",
            trigger: "change",
          },
          {
            validator: (rule, value, callback) => {
              if (!Number.isInteger(value) || value <= 0) {
                callback(new Error("学分必须是正整数"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        hours: [
          {
            required: true,
            type: "number",
            message: "请输入学时",
            trigger: "change",
          },
          {
            validator: (rule, value, callback) => {
              if (!Number.isInteger(value) || value <= 0) {
                callback(new Error("学时必须是正整数"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        deptId: [
          { required: true, message: "请选择开设院系", trigger: "change" },
        ],
      },
    };
  },

  created() {
    this.getTableData();
    if (this.departments.length === 0) {
      this.getAllDeptInfo();
    }
  },
  methods: {
    // 获取所有系的id和name
    getAllDeptInfo() {
      this.$store.dispatch("dept/getAllDept");
    },
    // 删除课程
    async deleteCourse(row) {
      const { deptId, courseId } = row;

      try {
        await this.$confirm(
          `确定要删除课程 "${row.courseName}" 吗？`,
          "删除确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 用户点击后执行删除操作
        const res = await deleteCourse(deptId, courseId);
        if (res.code === 200) {
          this.$message.success(res.data);
          // 判断是否为最后一页的最后一条
          if (this.tableData.length === 1 && this.pageNo > 1) {
            this.pageNo--;
          }
          this.getTableData();
        } else {
          this.$message.error(res.msg);
        }
      } catch (err) {
        this.$message.info("已取消删除");
      }
    },
    // 处理取消按钮点击
    handleCancel() {
      this.dialogVisible = false;
      this.$refs.courseForm.resetFields();
    },

    // 处理对话框关闭
    handleDialogClose() {
      this.$refs.courseForm.resetFields();
    },

    handleAdd() {
      // 清空表单数据
      this.form = {
        id: null,
        courseName: "",
        courseNo: "",
        credit: 1,
        hours: 1,
        deptId: null,
      };
      this.dialogVisible = true;
    },

    // 修改课程
    updateCourse(row) {
      this.dialogVisible = true;
      // 使用深拷贝防止直接修改原数据
      this.form = JSON.parse(JSON.stringify(row));
      this.form.id = row.courseId;
    },

    saveCourse() {
      this.$refs.courseForm.validate(async (valid) => {
        if (valid) {
          try {
            let res = await addCourse(this.form);
            if (res.code == 200) {
              this.$message.success(res.data);
              this.dialogVisible = false;
              this.getTableData();
            } else {
              this.$message.error(res.msg);
            }
          } catch (error) {
            this.$message.error("保存失败");
          }
        } else {
          return false;
        }
      });
    },

    // 获取表格数据
    async getTableData() {
      this.searchForm.pageNo = this.pageNo;
      this.searchForm.pageSize = this.pageSize;
      try {
        let res = await getAllDeptCourseDetail(this.searchForm);
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      } catch (error) {}
    },

    handleSearch() {
      this.getTableData();
    },

    selectChange() {
      this.getTableData();
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.getTableData();
    },

    handleCurrentChange(page) {
      this.pageNo = page;
      this.getTableData();
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  margin: 20px;

  .search-bar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .label {
    margin-right: 8px;
  }

  .input {
    width: 200px;
    margin-right: 20px;
  }

  .select {
    width: 200px;
    margin-right: 20px;
  }

  .add-btn {
    margin-left: auto;
  }
}
</style>